package com.roger.springGreenwich.gateway.filter;

import com.roger.springGreenwich.gateway.util.MonoUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

@RefreshScope
@Component
@Order(-100)
public class TokenFilter implements GlobalFilter {
    @Value("${validate.url}")
    private List<String> validateUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)  {
        String requestUrl = exchange.getRequest().getPath().value();
        //System.out.println("-100request url===" + requestUrl);

        //1 uaa服务所有放行
        if (validateUrl(requestUrl)) {
            System.out.println("不用验证token");
            return chain.filter(exchange);
        }else{
            return MonoUtil.buildReturnMono(exchange,chain);
        }

    }

    private boolean validateUrl(String requestUrl){
        System.out.println(requestUrl);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        boolean result = false;
        for(String freeUrl : validateUrl){
            System.out.println(freeUrl + ":" + requestUrl);
            if(pathMatcher.match(freeUrl, requestUrl)){
                result = true;
                break;
            }
        }

        return result;

    }

}
